<template>
  <div>
    <!-- 面包屑导航 -->
    <bread />
    <!-- 卡片区域 -->
    <el-card>
      <el-row :class="['bdbottom']">
        <el-col>
          <el-button type="primary" @click="dialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色信息表格 -->
      <el-table :data="rolesList" border style="width: 100%">
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row
              :class="[
                'tags',
                'rowBottom',
                'rowleft',
                index1 === 0 ? 'rowTop' : '',
              ]"
              v-for="(item, index1) in scope.row.children"
              :key="item.id"
            >
              <el-col :span="8">
                <el-tag
                  closable
                  effect="dark"
                  @close="removeTag(scope.row, item)"
                >
                  {{ item.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="16">
                <el-row
                  :class="[
                    'rowleft',
                    'tags',
                    'rowRigth ',
                    index2 == 0 ? 'rowBottom' : 'rowTop',
                  ]"
                  v-for="(item2, index2) in item.children"
                  :key="item2.id"
                >
                  <!-- 二级权限 -->
                  <el-col :span="8" class="rowRight">
                    <el-tag
                      type="success"
                      closable
                      @close="removeTag(scope.row, item2)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="15" class="rowRight tags">
                    <el-tag
                      type="warning"
                      closable
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      @close="removeTag(scope.row, item3)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="data">
            <!-- 修改角色 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRole(data.row)"
              >编辑</el-button
            >
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delRole(data.row.id)"
              >删除</el-button
            >
            <!-- 分配权限按钮 -->
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="privileges(data.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加角色弹窗 -->
      <el-dialog title="添加角色" :visible.sync="dialogVisible" width="50%">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="ruleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="ruleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addrole">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改角色弹窗 -->
      <el-dialog title="添加角色" :visible.sync="editRoleVisible" width="50%">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="ruleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="ruleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editRoleVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRole">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="分配权限" :visible.sync="privilegesVisible" width="30%">
        <el-tree
          :data="rightsList"
          :props="treeProps"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="defkes"
          ref="treeRef"
        ></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="Savepermission = false">取 消</el-button>
          <el-button type="primary" @click="Savepermission()">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import bread from "../bread";
import Bread from "../bread.vue";
export default {
  data() {
    return {
      rolesList: [], //角色列表
      rightsList: [], //权限列表
      treeProps: {
        label: "authName",
        children: "children",
      }, //属性控件属性绑定
      defkes: [], //默认选中的节点id
      roleid: "",
      dialogVisible: false, //添加角色弹窗
      editRoleVisible: false, //修改角色弹窗
      privilegesVisible: false, //分配权限弹窗
      ruleForm: {
        roleName: "", //角色名称
        roleDesc: "", //角色描述
      },
      // 正则表达式
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 2,
            max: 8,
            message: "角色名称长度在2~8个字符之间",
            trigger: "blur",
          },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          {
            min: 1,
            max: 15,
            message: "角色描述长度在1~15个字符之间",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    //获取数据信息
    async getRolesList() {
      let res = await this.axios.get("/roles");
      let { data, meta } = res.data;
      if (meta.status !== 200) {
        this.$message.error(meta.msg);
      } else {
        this.rolesList = data;
      }
    },
    //添加角色
    addrole() {
      this.$refs.ruleForm.validate(async (vali) => {
        if (vali) {
          let res = await this.axios.post("roles", this.ruleForm);
          let { meta } = res.data;
          console.log(res);
          if (meta.status !== 201) {
            this.$message.error(meta.msg);
          } else {
            this.$message.success(meta.msg);
            this.getRolesList();
            this.ruleForm = {};
            this.dialogVisible = false;
          }
        }
      });
    },
    //删除角色
    delRole(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.axios.delete(`roles/${id}`).then((res) => {
            this.getRolesList();
          });
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //修改角色
    editRole(data) {
      this.ruleForm = JSON.parse(JSON.stringify(data));
      this.editRoleVisible = true;
    },
    //保存修改后的角色
    saveRole() {
      this.$refs.ruleForm.validate(async (vali) => {
        if (!vali) {
          return;
        } else {
          let res = await this.axios.put(
            `roles/${this.ruleForm.id}`,
            this.ruleForm
          );
          let { meta } = res.data;
          if (meta.status !== 200) {
            this.$message.error(meta.msg);
          } else {
            this.$message.success(meta.msg);
            this.getRolesList();
            this.editRoleVisible = false;
          }
        }
      });
    },
    //分配权限
    async privileges(role) {
      this.roleid = role.id;
      let res = await this.axios.get("rights/tree");
      let { data, meta } = res.data;
      this.rightsList = data;
      this.getLeafKeys(role, this.defkes);
      this.privilegesVisible = true;
    },
    //递归获取id
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr);
      });
    },
    // 保存分配权限
    Savepermission() {
      let keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(",");
      this.axios
        .post(`roles/${this.roleid}/rights`, {
          rids: idStr,
        })
        .then((res) => {
          let { meta } = res.data;
          if (meta.status !== 200) {
            this.$message.error(meta.msg);
          } else {
            this.$message.success(meta.msg);
            this.privilegesVisible = false;
            this.getRolesList();
          }
        });
    },
    // // 点击删除tag标签
    async removeTag(line, item) {
      const confirmText = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmText !== "confirm") {
        return this.$message.info("已取消删除！");
      } else {
        const { data: res } = await this.axios.delete(
          `roles/${line.id}/rights/${item.id}`
        );
        console.log(res);
        if (res.meta.status !== 200) {
          this.$message.success(res.meta.msg);
        }
        line.children = res.data;
      }
    },
    // 点击删除当前行角色信息
    async del(id) {
      const confirmText = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmText !== "confirm") {
        return this.$message.info("已取消删除！");
      } else {
        const { data: res } = await this.axios.delete(`/roles/${id.id}`);
        if (res.meta.status !== 200) {
          this.$message.success(res.meta.msg);
        }
        this.$message.success(res.meta.msg);
        this.getRolesList();
      }
    },
  },
  //面包屑导航
  components: {
    bread,
  },
};
</script>
<style lang="scss" scoped>
.el-card {
  margin-top: 15px;
}
.el-row {
  margin-bottom: 15px;
}
.el-tag {
  margin: 7px;
}
.rowTop {
  border-top: 1px solid #eee;
}
.rowBottom {
  border-bottom: 1px solid #eee;
}
.rowRigth {
  border-right: 1px solid #eee;
}
.rowleft {
  border-left: 1px solid #eee;
}
</style>